package dongze.com.ckdj.activity;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.databinding.DataBindingUtil;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.GridLayout;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import dongze.com.ckdj.CKDJApplication;
import dongze.com.ckdj.R;
import dongze.com.ckdj.dagger.component.SectionComponent;
import dongze.com.ckdj.dagger.component.UserComponent;
import dongze.com.ckdj.data.entity.response.User;
import dongze.com.ckdj.databinding.InformationItemTextBinding;
import dongze.com.ckdj.databinding.model.InformationItemTextModel;
import dongze.com.ckdj.fragment.UserConfigurationFragment;
import dongze.com.ckdj.util.MyLog;
import dongze.com.ckdj.util.Util;


/**
 * Created by fanqwz on 2017/8/10.
 */

public class UserPreferenceActivity extends Activity {
    private static final String TAG = UserPreferenceActivity.class.getSimpleName();
    @Inject
    User mUser;
    InformationItemTextModel mTimeModel = new InformationItemTextModel();
    InformationItemTextModel mUserModel = new InformationItemTextModel();
    @BindView(R.id.basic_info_container)
    GridLayout mBasicInfoLayout;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        MyLog.d(TAG, "onCreate: ");
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        android.app.ActionBar actionBar = getActionBar();
        actionBar.setCustomView(R.layout.action_bar);
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowHomeEnabled(true);

        setContentView(R.layout.activity_preference);
        ButterKnife.bind(this);

        if (savedInstanceState == null) {
            android.app.FragmentTransaction transaction = getFragmentManager().beginTransaction();
            transaction.add(R.id.content, new UserConfigurationFragment());
            transaction.commitAllowingStateLoss();
        }

        initData();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_TIME_TICK);
        registerReceiver(mTimeReceiver, intentFilter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.configuration_activity_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.close) {
            finish();
            return true;
        } else if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (((CKDJApplication) getApplication()).getComponent(UserComponent.class) == null)
            finish();
    }

    @Override
    protected void onDestroy() {
        MyLog.d(TAG, "onDestroy: " + this);
        ((CKDJApplication) getApplication()).addComponent(SectionComponent.class, null);
        unregisterReceiver(mTimeReceiver);
        super.onDestroy();
    }

    private void initData() {
        CKDJApplication application = (CKDJApplication) getApplication();

        if (application.getComponent(UserComponent.class) != null) {
            application.getComponent(UserComponent.class).inject(this);
        }

        if (mUser == null) {
            MyLog.e(TAG, "onCreate: user null, activity finished");
            new AlertDialog.Builder(this)
                    .setMessage("user null")
                    .setCancelable(false)
                    .setNegativeButton("exit", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .create()
                    .show();
            return;
        }

        mTimeModel.setKey("当前时间");
        mTimeModel.setValue(Util.getCurrentTime(this));
        addBasicInfoItem(mTimeModel);

        mUserModel.setKey("登陆人员");
        mUserModel.setValue(mUser.getRemark() + "-" + mUser.getUser_name());
        addBasicInfoItem(mUserModel);

    }

    private void addBasicInfoItem(InformationItemTextModel model) {
        InformationItemTextBinding binding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.information_item_text, mBasicInfoLayout, false);
        binding.getRoot().setTag(binding);
        binding.setVehicleInformationItemText(model);
        int count = mBasicInfoLayout.getColumnCount();
        GridLayout.LayoutParams params = new GridLayout.LayoutParams(GridLayout.spec(mBasicInfoLayout.getChildCount() / count, 1), GridLayout.spec(mBasicInfoLayout.getChildCount() % count, 1));
        params.width = (getResources().getDisplayMetrics().widthPixels) / count;

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            params = new GridLayout.LayoutParams(GridLayout.spec(mBasicInfoLayout.getChildCount() / count, 1, 0.5f), GridLayout.spec(mBasicInfoLayout.getChildCount() % count, 1, 0.5f));
//        }

        int margin = getResources().getDimensionPixelSize(R.dimen.basic_info_item_margin);
        params.setMargins(margin, margin, margin, margin);
        mBasicInfoLayout.addView(binding.getRoot(), params);
    }

    BroadcastReceiver mTimeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
                mTimeModel.setValue(Util.getCurrentTime(UserPreferenceActivity.this));
            }
        }
    };
}
